"""
人脸识别API服务 - 应用入口
FastAPI应用程序主入口
"""
import uvicorn
from fastapi import FastAPI
from contextlib import asynccontextmanager

from config.settings import settings
from utils.logger import app_logger
from database.connection import init_database
from api import face_api, health_api
from api.middleware import setup_cors, log_middleware, error_handler_middleware


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    app_logger.info("="*50)
    app_logger.info(f"{settings.app_name} v{settings.app_version} 启动中...")
    app_logger.info(f"环境: {settings.app_env}")
    app_logger.info("="*50)

    try:
        # 初始化数据库
        init_database()
        app_logger.info("数据库初始化完成")

        # 其他初始化（人脸引擎和FAISS索引会自动初始化）
        app_logger.info("服务初始化完成")

    except Exception as e:
        app_logger.error(f"服务启动失败: {e}", exc_info=True)
        raise

    yield

    # 关闭时执行
    app_logger.info(f"{settings.app_name} 正在关闭...")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app_name,
    version=settings.app_version,
    description="基于insightface和FAISS的高性能人脸识别后台服务",
    lifespan=lifespan
)

# 配置CORS
setup_cors(app)

# 添加中间件
app.middleware("http")(log_middleware)
app.middleware("http")(error_handler_middleware)

# 注册路由
app.include_router(health_api.router)
app.include_router(face_api.router)


if __name__ == "__main__":
    """直接运行入口"""
    uvicorn.run(
        "main:app",
        host=settings.app_host,
        port=settings.app_port,
        reload=settings.debug,
        log_level=settings.log_level.lower()
    )
